package _interview150;

import _object.ListNode;

/**
 * 23. 合并 K 个升序链表
 */
public class No23 {
    private ListNode[] lists;

    public ListNode mergeKLists(ListNode[] lists) {
        this.lists = lists;
        return divide(0, lists.length - 1);
    }

    private ListNode divide(int left, int right) {
        if (left > right) return null;
        else if (left == right) return lists[left];
        int mid = left + (right - left) / 2;
        return sort(divide(left, mid), divide(mid + 1, right));
    }

    private ListNode sort(ListNode l1, ListNode l2) {
        ListNode cur = new ListNode(-1), dummy = cur;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = new ListNode(l1.val);
                l1 = l1.next;
            } else {
                cur.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            cur = cur.next;
        }
        if (l1 != null) cur.next = l1;
        if (l2 != null) cur.next = l2;
        return dummy.next;
    }
}
